package pers.cz.logtail.handle.adapter;

import pers.cz.config.JefConfiguration;
import pers.cz.netty.protocal.Message;
import pers.cz.util.FileUtils;
import pers.cz.util.LogConfigItem;

import java.io.File;
import java.util.Map;

/**
 * @program: JefLogTail
 * @description: 本地文件持久化保存
 * @author: Cheng Zhi
 * @create: 2023-03-04 20:41
 **/
public class LocalFileAdapter extends AbstractLogSaveAdapter {

    @Override
    public void save(Message message) {
        String fileName = "";
        String filePath = JefConfiguration.get(LogConfigItem.LOG_FILEPATH);
        // 获取到文件后，如果路径是文件则直接写入，如果是文件夹，则按照采集端ip+name的方式写入
        // File file = new File(filePath);
        // Linux下无法使用file.isDirectory()判断，所以采用配置文件指定的方式
        /*if (file.isDirectory()) {
            fileName = message.getAttachment("ip") + "_" + message.getAttachment("fileName");
            fileName = filePath + fileName;
        } else {
            fileName = filePath;
        }*/
        boolean isMerge = JefConfiguration.getBoolean(LogConfigItem.LOG_FILE_EMRGE, false);
        if (isMerge) {
            fileName = filePath;
        } else {
            fileName = message.getAttachment("ip") + "_" + message.getAttachment("fileName");
            fileName = filePath + fileName;
        }
        FileUtils.writeFileByStreamByRandomAccess(fileName, (String) message.getContent());

    }
}
